package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 拦截器Interceptor
 */
@Configuration //申明这是一个配置
public class MyMVCConfig implements WebMvcConfigurer {

    // 自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new MyHandlerInterceptor();
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/demo/*");
    }

    // 自定义消息转化器的第二种方法
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(converter);
    }



    private void log(String str) {
        System.out.println(str);
    }

    public class MyHandlerInterceptor implements HandlerInterceptor {

        /*核心方法，请求处理器，只有该方法返回true，才会继续执行后续的Controller。*/
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            log("自定义拦截器............");
            response.addHeader("BB", "aaa");
            String requestURI = request.getRequestURI();
            log(requestURI);
            if (requestURI.endsWith("demo3")) {
                request.getRequestDispatcher("/demo/fail").forward(request, response);
                /*java.lang.IllegalStateException: Cannot forward after response has been committed*/
                return false;
            }
            return true;
        }
        /*DispatcherServlet进行视图返回渲染之前进行调用*/
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
            log("postHandle");
//            response.addHeader("AA", "aaa"); /*这里设置的客户端收不到*/
        }
        /*在DispatcherServlet 渲染了对应的视图之后执行。用于进行资源清理*/
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                    Exception ex) throws Exception {
            log("afterCompletion");
        }

    }
}